package flc.ast.fragment;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;
import com.google.gson.reflect.TypeToken;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.SignInRecordActivity;
import flc.ast.adapter.CalendarAdapter;
import flc.ast.bean.MyCalendarBean;
import flc.ast.databinding.FragmentSignInBinding;
import flc.ast.utils.AppSpUtils;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.StatusBarUtils;
import stark.common.bean.StkResBean;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SignInFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SignInFragment extends BaseNoModelFragment<FragmentSignInBinding> {

    private CalendarAdapter calendarAdapter;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
    private boolean isSignIn = false;
    private Dialog mySelMonthDialog;
    private WheelView wheelView1, wheelView2;

    @Override
    protected int onCreate() {
        return R.layout.fragment_sign_in;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.rvCalendarList.setLayoutManager(new GridLayoutManager(mContext, 7));
        calendarAdapter = new CalendarAdapter();
        mDataBinding.rvCalendarList.setAdapter(calendarAdapter);
        mDataBinding.ivRecord.setOnClickListener(this);
        mDataBinding.ivSignIn.setOnClickListener(this);
        mDataBinding.tvMonth.setOnClickListener(this);
        //选择年月弹框
        selMonthDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivRecord://签到记录
                startActivity(SignInRecordActivity.class);
                break;
            case R.id.ivSignIn://签到
                if (!isSignIn) {
                    List<String> listSp = AppSpUtils.getSignIntList();
                    if (listSp != null && listSp.size() > 0) {
                        listSp.add(TimeUtils.getNowString(format));
                        AppSpUtils.savSignInList(listSp);
                    } else {
                        List<String> listSave = new ArrayList<>();
                        listSave.add(TimeUtils.getNowString(format));
                        AppSpUtils.savSignInList(listSave);
                    }
                }
                showRecord();
                break;
            case R.id.tvMonth://选择年月
                mySelMonthDialog.show();
                break;
            //选择日期弹框
            case R.id.tvDialogSelMonthCancel://取消
                mySelMonthDialog.dismiss();
                break;
            case R.id.tvDialogSelMonthRight://确定
                mySelMonthDialog.dismiss();
                int year = wheelView1.getCurrentItem() + 1980;
                int moon = wheelView2.getCurrentItem() + 1;
                String selDate = year + "年" + (moon < 10 ? "0" + moon : moon) + "月";
                mDataBinding.tvMonth.setText(selDate);
                setDay(moon, year);//设置日历
                //默认选中显示今天的日期记录
                setShowNowDay(year + "." + moon + ".");
                showRecord();
                break;
        }
    }

    @Override
    protected void initData() {
        mDataBinding.tvMonth.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy年MM月")));//当前年月
        int year = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("yyyy")));//获取当前年份
        int moon = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("M")));//获取当前月份
        int day = Integer.parseInt(TimeUtils.getNowString(new SimpleDateFormat("d")));//获取当前天数
        setDay(moon, year);//设置日历
        //默认选中显示今天的日期记录
        setShowNowDay(year + "." + moon + ".");
        showRecord();
    }

    //设置日期数据
    private void setDay(int moon, int year) {
        //获取天数
        int dayNum = getDayNum(moon,year);
        //获取需要空出的天数
        int weekNum = getWeekNum(moon, year);
        //生成日历表
        List<MyCalendarBean> listDay = new ArrayList<>();
        for (int i = 0; i < 42; i++) {
            if (i <= weekNum || i > dayNum + weekNum) {
                listDay.add(new MyCalendarBean("", i, false, false));//空
            } else {
                listDay.add(new MyCalendarBean(i - weekNum + "", i, false, false));
            }
        }
        calendarAdapter.setList(listDay);
    }

    //判断该月有多少天
    private int getDayNum(int moon,int year) {
        int dayNum = 31;
        if (moon == 1 || moon == 3 || moon == 5 || moon == 7 || moon == 8 || moon == 10 || moon == 12) {
            //大月31天
            dayNum = 31;
        } else if (moon == 2) {
            //2月判断是闰(29)还是平(28)
            if ((year % 4 == 0 && year % 100 != 0 || (year % 400 == 0))) {
                dayNum = 29;
            } else {
                dayNum = 28;
            }
        } else {
            //小月30天
            dayNum = 30;
        }
        return dayNum;
    }

    //获取该月第一天是星期几（当天要算上 所以少减一天）
    private int getWeekNum(int moon, int year) {
        int weekNum = 0;
        String week = TimeUtils.getChineseWeek(year + "." + moon + ".01", format);
        if (week.equals(getString(R.string.monday_text))) {
            weekNum = 0;
        } else if (week.equals(getString(R.string.tuesday_text))) {
            weekNum = 1;
        } else if (week.equals(getString(R.string.wednesday_text))) {
            weekNum = 2;
        } else if (week.equals(getString(R.string.thursday_text))) {
            weekNum = 3;
        } else if (week.equals(getString(R.string.friday_text))) {
            weekNum = 4;
        } else if (week.equals(getString(R.string.saturday_text))) {
            weekNum = 5;
        } else if (week.equals(getString(R.string.sunday_text))) {
            weekNum = 6;
        }
        return weekNum;
    }

    //显示今天
    private void setShowNowDay(String date) {
        for (MyCalendarBean bean : calendarAdapter.getValidData()) {
            if (!TextUtils.isEmpty(bean.getDate())) {
                String nowDate = date + bean.getDate();
                if (nowDate.equals(TimeUtils.getNowString(new SimpleDateFormat("yyyy.M.d")))) {
                    bean.setSelect(true);
                    break;
                }
            }
        }
        calendarAdapter.notifyDataSetChanged();
    }

    //显示签到记录
    private void showRecord() {
        for (MyCalendarBean bean : calendarAdapter.getValidData()) {
            bean.setRecord(false);
        }
        String date = mDataBinding.tvMonth.getText().toString();
        List<String> listSp = AppSpUtils.getSignIntList();
        if (listSp != null && listSp.size() > 0) {
            for (String s : listSp) {
                for (MyCalendarBean dayBean : calendarAdapter.getValidData()) {
                    long millis1 = TimeUtils.string2Millis(s, format);
                    long millis2 = TimeUtils.string2Millis(date + dayBean.getDate() + "日", new SimpleDateFormat("yyyy年MM月dd日"));
                    if (millis1 == millis2) {
                        dayBean.setRecord(true);
                    }
                }
                if (s.equals(TimeUtils.getNowString(format))) {
                    isSignIn = true;
                    mDataBinding.ivSignIn.setImageResource(R.drawable.an_qd2);
                }
            }
        } else {
            isSignIn = false;
            mDataBinding.ivSignIn.setImageResource(R.drawable.an_qd1);
        }
        calendarAdapter.notifyDataSetChanged();
    }

    //选择年月弹框
    private void selMonthDialog() {
        mySelMonthDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_month, null);
        mySelMonthDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySelMonthDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogSelMonthCancel);
        TextView dialogRight = inflate.findViewById(R.id.tvDialogSelMonthRight);
        wheelView1 = inflate.findViewById(R.id.wheel_view1);
        wheelView2 = inflate.findViewById(R.id.wheel_view2);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView1.setDividerColor(Color.parseColor("#66457096"));
        wheelView1.setTextColorCenter(Color.parseColor("#0F3C73"));
        wheelView1.setLineSpacingMultiplier(2.5f);
        wheelView1.setDividerType(WheelView.DividerType.WRAP);
        wheelView1.setDividerColor(Color.parseColor("#4DFF83B3"));
        wheelView1.setCurrentItem(43);
        wheelView1.setItemsVisibleCount(3);
        wheelView1.setCyclic(true);
        wheelView1.setTextSize(16);
        wheelView1.setTypeface(Typeface.DEFAULT_BOLD);
        wheelView2.setDividerColor(Color.parseColor("#66457096"));
        wheelView2.setTextColorCenter(Color.parseColor("#0F3C73"));
        wheelView2.setLineSpacingMultiplier(2.5f);
        wheelView2.setDividerType(WheelView.DividerType.WRAP);
        wheelView2.setDividerColor(Color.parseColor("#4DFF83B3"));
        wheelView2.setCurrentItem(0);
        wheelView2.setItemsVisibleCount(3);
        wheelView2.setCyclic(true);
        wheelView2.setTextSize(16);
        wheelView2.setTypeface(Typeface.DEFAULT_BOLD);
        //设置滚轮数据
        List<String> listYear = new ArrayList<>();//年 1980-2040
        for (int i = 0; i < 61; i++) {
            listYear.add(String.valueOf(1980 + i));
        }
        List<String> listMonth = new ArrayList<>();//月 12
        for (int i = 0; i < 12; i++) {
            listMonth.add(String.valueOf((i + 1) < 10 ? "0" + (i + 1) : i + 1));
        }
        WheelAdapter adapter1 = new ArrayWheelAdapter(listYear);
        wheelView1.setAdapter(adapter1);
        WheelAdapter adapter2 = new ArrayWheelAdapter(listMonth);
        wheelView2.setAdapter(adapter2);
        //滚动到对应日期
        String date = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        String[] split = date.split("-");
        int year = Integer.parseInt(split[0]);//年
        int moon = Integer.parseInt(split[1]);//月
        wheelView1.setCurrentItem(year - 1980);
        wheelView2.setCurrentItem(moon - 1);
    }

}